import React from 'react'
import BaseStore from '@/base/BaseStore'
import { Message } from '@biz/Components'

export default class Store extends BaseStore {
  constructor(props, config, action) {
    super(props, config, action)
    this.state = this.getInitialState()
  }

  getInitialSo() {
    return {
      couponQuantityEditable: false,
    }
  }

  onGetUserInfo(phone) {
    this.setState({ phone, loading: true, user: null })
  }

  onGetUserInfoCompleted(res) {
    this.setState({ loading: false })
    super.dealResponse(res, () => {
      this.setState({ user: res.vo })
    })
  }
  onGetAllVipProductListCompleted(res) {
    this.setState({ loading: false })
    super.dealResponse(res, () => {
      this.setState({ vipProductList: res.voList })
    })
  }

  onMockRecharge() {
    this.setState({ rechargeLoading: true })
  }

  onMockRechargeCompleted(res) {
    this.setState({ rechargeLoading: false })
    super.dealResponse(res, () => {
      this.Action.getUserInfo(this.state.phone)
    })
  }

  onMockVip() {
    this.setState({ vipLoading: true })
  }

  onMockVipCompleted(res) {
    this.setState({ vipLoading: false })
    super.dealResponse(res, () => {
      this.Action.getUserInfo(this.state.phone)
    })
  }

  // 获取优惠券列表
  onGetAllCouponListCompleted(res) {
    this.setState({ loading: false })
    super.dealResponse(res, () => {
      const list = res?.vo?.couponList || res.list || []
      const options = list.map((item) => ({
        ...item,
        label: item.name,
        id: item?.value,
      }))
      this.setState({ couponList: options })
    })
  }

  // 发券
  onIssueCoupon() {
    this.setState({ couponLoading: true })
  }

  onIssueCouponCompleted(res) {
    this.setState({ couponLoading: false })
    if (res && res.success) {
      Message.success('发券成功')
      // 设置成功标志，用于触发表单清除
      this.setState({ issueCouponSuccess: true })
      // 延迟重置标志，避免重复触发
      setTimeout(() => {
        this.setState({ issueCouponSuccess: false })
      }, 100)
      // 刷新用户信息
      if (this.state.phone) {
        this.Action.getUserInfo(this.state.phone)
      }
    } else {
      Message.error(res?.errMsg || '发券失败')
      this.setState({ issueCouponSuccess: false })
    }
  }

  onIssueCouponFailed(error) {
    this.setState({ couponLoading: false })
    Message.error('发券失败：' + (error?.message || '网络错误'))
  }
}
